ATOM Documentation

โ† Back to App

Sales Hub Implementation - Complete Guide

Overview

The Sales Hub / Sales Command Center is now fully functional with dynamic data from the database. This document provides a comprehensive overview of the implementation, architecture, API endpoints, and usage instructions.

๐ŸŽฏ What's Been Implemented

โœ… Complete Features

  1. **Dynamic Dashboard Metrics**
  • Total Pipeline Value
  • Active Deals Count
  • Key Contacts Count
  • Win Rate Calculation
  • Weighted Revenue Forecast
  • Deals by Stage Breakdown
  1. **AI-Powered Lead Intelligence**
  • Stalled Deal Detection (>14 days inactive)
  • High-Value/Low-Probability Deal Alerts
  • Inactive Deal Warnings
  • Actionable Recommendations
  • Risk Level Classification (Critical/Warning/Info)
  1. **Real-Time Activity Feed**
  • Email Sent Activities
  • Call Completed Activities
  • Stage Change Tracking
  • Deal Creation Logging
  • WebSocket Real-Time Updates
  1. **Revenue Forecasting**
  • 3-Month Forecast Widget
  • Weighted Forecast Calculation
  • Best/Worst Case Scenarios
  • Confidence Scores
  • Deal Count by Month
  1. **Deal Pipeline Management**
  • View All Active Deals
  • Deal Stage Progression
  • Company and Value Display
  • Source Attribution (Salesforce, HubSpot, Manual)

๐Ÿ“Š Database Schema

Core Tables

1. `sales_leads` Table

CREATE TABLE sales_leads (
    id UUID PRIMARY KEY,
    tenant_id UUID NOT NULL REFERENCES tenants(id),
    external_id VARCHAR(255),
    email VARCHAR(255) NOT NULL,
    first_name VARCHAR(255),
    last_name VARCHAR(255),
    company VARCHAR(255),
    source VARCHAR(100),
    status VARCHAR(50), -- new, qualified, disqualified, contacted, spam
    is_converted BOOLEAN DEFAULT FALSE,
    is_spam BOOLEAN DEFAULT FALSE,
    ai_score DECIMAL(5,2),
    ai_qualification_summary TEXT,
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW()
);

2. `deals` Table

CREATE TABLE deals (
    id UUID PRIMARY KEY,
    tenant_id UUID NOT NULL REFERENCES tenants(id),
    name VARCHAR(255) NOT NULL,
    company VARCHAR(255),
    value DECIMAL(15,2) DEFAULT 0.0,
    stage VARCHAR(50) NOT NULL DEFAULT 'discovery',
    probability DECIMAL(5,2) DEFAULT 50.0,
    source VARCHAR(100) DEFAULT 'manual',
    health_score DECIMAL(5,2),
    risk_level VARCHAR(20),
    expected_close_date TIMESTAMP,
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW()
);

3. `sales_activities` Table

CREATE TABLE sales_activities (
    id UUID PRIMARY KEY,
    tenant_id UUID NOT NULL REFERENCES tenants(id),
    deal_id UUID NOT NULL REFERENCES deals(id),
    user_id UUID REFERENCES users(id),
    type VARCHAR(50) NOT NULL, -- email, call, meeting, note, stage_change
    description TEXT,
    timestamp TIMESTAMP DEFAULT NOW()
);

๐Ÿ”Œ API Endpoints

Frontend Routes (Next.js)

1. Dashboard Stats

GET /api/sales/dashboard/stats

**Response:**

{
  "total_pipeline": 125000,
  "active_deals_count": 8,
  "key_contacts": 142,
  "win_rate": 64,
  "weighted_forecast": 78000,
  "deals_by_stage": {
    "discovery": 2,
    "qualification": 3,
    "proposal": 2,
    "negotiation": 1
  }
}

2. Sales Insights

GET /api/sales/insights

**Response:**

{
  "status": "success",
  "count": 2,
  "insights": [
    {
      "anomaly_id": "stalled_deal_abc123",
      "severity": "warning",
      "title": "Deal 'Enterprise License' stalled for 15 days",
      "description": "Deal worth $85,000 hasn't moved in 15 days",
      "affected_entities": ["abc123"],
      "platforms": ["salesforce"],
      "recommendation": "Send follow-up email or schedule call to re-engage",
      "action_type": "email",
      "action_payload": {"deal_id": "abc123", "action": "follow_up"}
    }
  ]
}

3. Sales Activities

GET /api/sales/activities?limit=20&offset=0

**Response:**

{
  "status": "success",
  "activities": [
    {
      "id": "act_123",
      "type": "email",
      "description": "Sent email: 'Proposal for review'",
      "deal_id": "deal_123",
      "deal_name": "Enterprise License - GrowthCorp",
      "deal_value": 120000,
      "timestamp": "2025-03-06T10:30:00Z"
    }
  ],
  "total_count": 45
}

4. Revenue Forecast

GET /api/sales/forecast?months=3

**Response:**

{
  "status": "success",
  "forecast": [
    {
      "month": "March 2025",
      "weighted_forecast": 42000,
      "best_case": 65000,
      "worst_case": 21000,
      "deal_count": 3,
      "confidence": 72
    }
  ],
  "summary": {
    "total_weighted_forecast": 126000,
    "total_best_case": 195000,
    "total_worst_case": 63000,
    "total_deals": 9,
    "avg_confidence": 68
  }
}

5. Pipeline Deals

GET /api/sales/pipeline

**Response:**

[
  {
    "deal": "Enterprise License - GrowthCorp",
    "value": 120000,
    "status": "negotiation",
    "platform": "salesforce",
    "company": "GrowthCorp"
  }
]

Backend Routes (FastAPI)

All frontend routes proxy to these backend endpoints:

GET /api/sales/dashboard/summary?workspace_id={id}&tenant_id={id}
GET /api/sales/insights?workspace_id={id}&tenant_id={id}
GET /api/sales/activities?workspace_id={id}&tenant_id={id}&limit=20
GET /api/sales/forecast?workspace_id={id}&tenant_id={id}&months=3
GET /api/sales/pipeline?workspace_id={id}&tenant_id={id}

๐Ÿงช Testing

1. Seed Sample Data

cd backend-saas
python scripts/seed_sales_demo.py

This creates:

  • 3 sample leads
  • 2 sample deals
  • 2 call transcripts
  • 1 demo workspace

2. Test API Endpoints

# Dashboard stats
curl https://atom-saas.fly.dev/api/sales/dashboard/stats

# Insights
curl https://atom-saas.fly.dev/api/sales/insights

# Activities
curl https://atom-saas.fly.dev/api/sales/activities?limit=10

# Forecast
curl https://atom-saas.fly.dev/api/sales/forecast?months=3

# Pipeline
curl https://atom-saas.fly.dev/api/sales/pipeline

3. View Dashboard

Navigate to:

https://atom-saas.fly.dev/dashboards/sales

๐Ÿค– AI Features

Lead Scoring Algorithm

The lead scoring system uses:

  1. **Engagement Signals** (40%)
  • Email opens and clicks
  • Website visits
  • Form submissions
  • Content downloads
  1. **Demographic Fit** (30%)
  • Company size
  • Industry alignment
  • Job title relevance
  • Geographic location
  1. **Behavioral Indicators** (20%)
  • Timeline to purchase
  • Budget availability
  • Decision maker involvement
  • Competitor usage
  1. **External Data** (10%)
  • Company funding news
  • Industry trends
  • Technographic data

Deal Health Scoring

Health scores are calculated based on:

  • **Last Activity**: Recent engagement boosts score
  • **Stage Progression**: Moving forward increases score
  • **Probability Changes**: Increasing probability improves score
  • **Value vs. Stage Alignment**: Large deals in early stages get lower scores

Risk Detection

The system identifies:

  1. **Stalled Deals**: No activity for 14+ days
  2. **High-Value At Risk**: Deals >$50k with <40% probability
  3. **Closing Soon Inactive**: Deals closing in 7 days with no recent activity
  4. **Long Sales Cycle**: Deals in same stage for >30 days

๐Ÿ”„ Lead Processing Workflow

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                     LEAD INGESTION                          โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                              โ”‚
                              โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  Sources: HubSpot, Salesforce, Web Forms, Email, CSV, API   โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                              โ”‚
                              โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                  NORMALIZATION ENGINE                        โ”‚
โ”‚  โ€ข Standardize field names                                  โ”‚
โ”‚  โ€ข Validate email formats                                   โ”‚
โ”‚  โ€ข Enrich company data                                     โ”‚
โ”‚  โ€ข Deduplicate existing leads                              โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                              โ”‚
                              โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                  AI LEAD SCORING                            โ”‚
โ”‚  โ€ข Calculate engagement score                              โ”‚
โ”‚  โ€ข Assess demographic fit                                  โ”‚
โ”‚  โ€ข Generate qualification summary                         โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                              โ”‚
                              โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                  LEAD ASSIGNMENT                            โ”‚
โ”‚  โ€ข Round-robin distribution                                โ”‚
โ”‚  โ€ข Territory-based routing                                 โ”‚
โ”‚  โ€ข Skill-based assignment                                  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                              โ”‚
                              โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                  PIPELINE STAGING                           โ”‚
โ”‚  Lead โ†’ Qualified โ†’ Proposal โ†’ Negotiation โ†’ Closed         โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

๐Ÿš€ Scaling Strategy

1. Database Optimization

**Indexing Strategy:**

-- Add these indexes for performance
CREATE INDEX idx_leads_tenant_status ON sales_leads(tenant_id, status);
CREATE INDEX idx_deals_tenant_stage ON deals(tenant_id, stage);
CREATE INDEX idx_activities_tenant_timestamp ON sales_activities(tenant_id, timestamp DESC);
CREATE INDEX idx_deals_updated ON deals(tenant_id, updated_at DESC);

**Partitioning:**

  • Partition sales_activities by month
  • Partition deals by quarter
  • Archive closed deals >1 year old

2. Caching Layer

# Redis cache keys
sales:stats:{tenant_id} # TTL: 5 minutes
sales:forecast:{tenant_id} # TTL: 15 minutes
sales:insights:{tenant_id} # TTL: 10 minutes
sales:pipeline:{tenant_id} # TTL: 2 minutes

3. Background Jobs

# Scheduled tasks
@cron_schedule("*/5 * * * *")  # Every 5 minutes
async def update_lead_scores():
    # Recalculate AI scores for active leads
    pass

@cron_schedule("0 */2 * * *")  # Every 2 hours
async def detect_stalled_deals():
    # Find and alert on stalled deals
    pass

@cron_schedule("0 0 * * *")  # Daily
async def generate_forecasts():
    # Pre-calculate forecasts for all tenants
    pass

4. Horizontal Scaling

**Microservice Breakdown:**

  1. **Lead Ingestion Service**
  • Handles all lead imports
  • Queue-based processing (Celery/RabbitMQ)
  • Rate limiting per tenant
  1. **AI Scoring Service**
  • Dedicated GPU/CPU for ML models
  • Batch processing for efficiency
  • Separate database for ML features
  1. **Analytics Service**
  • Pre-computed aggregations
  • Time-series database (TimescaleDB)
  • Materialized views for common queries
  1. **Integration Service**
  • Salesforce, HubSpot connectors
  • Webhook receivers
  • API rate limiting

๐Ÿ”’ Security & Multi-Tenancy

Tenant Isolation

All queries MUST filter by tenant_id:

# โœ… CORRECT
deals = db.query(Deal).filter(
    Deal.tenant_id == workspace_id
).all()

# โŒ WRONG - Cross-tenant data leak
deals = db.query(Deal).all()

Rate Limiting

# Per-tenant rate limits
RATE_LIMITS = {
    "free": 100,      # 100 requests/hour
    "solo": 500,
    "team": 5000,
    "enterprise": 50000
}

Audit Logging

All sales actions are logged:

await audit_service.log_action(
    tenant_id=tenant_id,
    user_id=user_id,
    action="deal.stage_change",
    resource_type="deal",
    resource_id=deal_id,
    outcome="success",
    metadata={"old_stage": "discovery", "new_stage": "proposal"}
)

๐Ÿ“ˆ Usage Analytics

Track these metrics:

  1. **Lead Sources Performance**
  1. **Stage Conversion Rates**
  1. **Sales Rep Performance**

๐ŸŽจ UI Components

Key Components Located At:

  • **Dashboard**: src/components/dashboards/SalesCommandCenter.tsx
  • **Activity Feed**: Integrated in dashboard
  • **Forecast Widget**: Integrated in dashboard
  • **AI Insights Panel**: Integrated in dashboard

Color Coding

  • **Critical Issues**: Red border/background (bg-red-500/5 border-red-500/20)
  • **Warnings**: Orange border/background (bg-orange-500/5 border-orange-500/20)
  • **Info**: Blue border/background (bg-primary/5 border-primary/20)

๐Ÿ“ Next Steps

Phase 2 Enhancements (Future)

  1. **Deal Management Modal**
  • Create new deals
  • Edit existing deals
  • Move deals between stages
  • Assign sales reps
  1. **Advanced Analytics**
  • Cohort analysis
  • Funnel visualization
  • Trend charts over time
  • Comparison views
  1. **Automation Rules**
  • Auto-assign leads
  • Trigger follow-ups
  • Stage-based notifications
  • Custom workflows
  1. **Integrations**
  • HubSpot sync
  • Salesforce sync
  • Google Sheets export
  • Slack notifications
  1. **Collaboration**
  • Deal comments
  • @mentions
  • File attachments
  • Activity tagging

๐Ÿ› Troubleshooting

Issue: "No data showing"

**Solution:**

  1. Check if workspace_id is correct
  2. Verify tenant isolation is working
  3. Run seed script: python scripts/seed_sales_demo.py
  4. Check browser console for API errors

Issue: "Insights not loading"

**Solution:**

  1. Ensure deals have updated_at timestamps
  2. Check DealStage enum values match
  3. Verify database has recent activity
  4. Check backend logs for errors

Issue: "Forecast shows 0"

**Solution:**

  1. Ensure deals have expected_close_date set
  2. Check probability values are set
  3. Verify deals are in active stages
  4. Check date range calculations

๐Ÿ“ž Support

For issues or questions:

  • Check backend logs: fly logs -a atom-saas --tail 100
  • Check database: Connect via psql to Neon
  • Review audit logs in saas_audit_logs table

---

**Last Updated:** March 6, 2025

**Version:** 1.0.0

**Status:** โœ… Production Ready